package control.micro
{
	import model.micro.Attackable;
	import model.micro.Battle;
	import model.micro.FieldUnit;
	
	/**
	 * The brain of a field unit.
	 *
	 * Knows what the field unit will do in the future. Field unit only knows its current state.
	 */
	public class FieldUnitController implements Updatable
	{
		/** The field unit this is controlling. */
		protected var unit:FieldUnit;
		/** The battle the unit is in */
		private var battle:Battle;
		/** 1 or -1 */
		private var forward:int;
		
		public var target:Attackable;
		
		/**
		 * Create a new controller for a specific field unit.
		 * @param	unit
		 */
		public function FieldUnitController(unit:FieldUnit, battle:Battle)
		{
			this.unit = unit;
			this.battle = battle;
			
			if (team == Battle.DEFENSE_TEAM)
				forward = 1.0;
			else if (team == Battle.ATTACK_TEAM)
				forward = -1.0;
		}
		
		private function get team():int
		{
			if (unit.macroUnit.owner == battle.defending_territory.owner) // defender
				return Battle.DEFENSE_TEAM;
			else // attacker
				return Battle.ATTACK_TEAM;
		}
		
		/**
		 * Called every frame.
		 */
		public function update():void
		{
			if (unit.macroUnit.owner == battle.defending_territory.owner) // defending
			{
				target = battle.getFirstAttacker();
			}
			else // attacking
			{
				target = battle.getFirstDefender();
			}
			
			if (target != null) {
				if (target.getBoundingBox().testCollision(unit.getBoundingBox())) {
					unit.attack(target);
				} else {
					unit.move(forward);
				}
			}
		}
		
		// TODO: Implement orders to give to field unit
		
		public function readyToRemove():Boolean
		{
			return unit.readyToRemove();
		}
	}

}